package com.example.homeworkdev.pages;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.homeworkdev.Dao.UserDao;
import com.example.homeworkdev.R;
import com.example.homeworkdev.entity.User;
import com.example.homeworkdev.util.UserInfoShared;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private RelativeLayout rootLayout;
    private AnimationDrawable backgroundAnimation;
    private LinearLayout llPhone, llPassword;
    private EditText etPhone, etPassword;
    private ImageView ivShowPwd;
    private Button btnLogin;
    private boolean isPasswordVisible = false;

    UserInfoShared userInfoShared =  new UserInfoShared();;

    // 初始化 UserDao
    private UserDao userDao = new UserDao(this);



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // 初始化视图
        rootLayout = findViewById(R.id.root_layout);
        llPhone = findViewById(R.id.ll_phone);
        llPassword = findViewById(R.id.ll_password);
        etPhone = findViewById(R.id.et_phone);
        etPassword = findViewById(R.id.et_password);
        ivShowPwd = findViewById(R.id.iv_show_pwd);
        btnLogin = findViewById(R.id.btn_login);

        // 启动背景动画
        backgroundAnimation = (AnimationDrawable) rootLayout.getBackground();
        backgroundAnimation.start();

        // 输入框聚焦动画
        setupFocusAnimation(llPhone, etPhone);
        setupFocusAnimation(llPassword, etPassword);

        isRememberMe();

        // 显示/隐藏密码
        ivShowPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isPasswordVisible = !isPasswordVisible;
                etPassword.setInputType(isPasswordVisible ?
                        InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD :
                        InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                etPassword.setSelection(etPassword.getText().length()); // 保持光标位置
                ivShowPwd.setImageResource(isPasswordVisible ?
                        R.drawable.ic_eye_show : R.drawable.ic_eye_hide);
            }
        });

        // 登录按钮点击事件
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = etPhone.getText().toString().trim();
                String password = etPassword.getText().toString().trim();

                if (TextUtils.isEmpty(phone)) {
                    Toast.makeText(LoginActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(password)) {
                    Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 模拟登录加载动画
                btnLogin.setEnabled(false);
                btnLogin.setText("登录中...");
                btnLogin.setBackgroundResource(R.drawable.btn_login_loading);

                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                    // 延迟2秒执行任务
                    boolean success = userDao.loginUser(phone, password);
                    if (success) {
                        clearFields();
                        Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

                        CheckBox checkBox = findViewById(R.id.cb_remember);
                        isRememberMe();
                        // 保存用户信息到SharedPreferences
                        userInfoShared.saveUserInfo(LoginActivity.this,phone,password,checkBox.isChecked());

                        // 登录成功，跳转到主页
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        Toast.makeText(LoginActivity.this, "账号密码错误", Toast.LENGTH_SHORT).show();
                        btnLogin.setEnabled(true);
                        btnLogin.setText("登录");
                        btnLogin.setBackgroundResource(R.drawable.btn_login_selector);
                    }

                }, 2000);

            }
        });
    }

    //记住我
    private void isRememberMe() {
        SharedPreferences preferences = getSharedPreferences("UserPrefs", Context.MODE_PRIVATE);
        CheckBox checkBox = findViewById(R.id.cb_remember);
        TextView pwd = findViewById(R.id.et_password);
        TextView name = findViewById(R.id.et_phone);

        if(preferences.getBoolean("rememberMe",false) || checkBox.isChecked()){
            User user = userInfoShared.getUserInfo(this);
            //勾选了记住我
            name.setText(user.getPhone());
            pwd.setText(user.getPassword());
            checkBox.setChecked(true);
        }else{
            pwd.setText("");
            name.setText("");
            checkBox.setChecked(false);
        }

    }

    private void clearFields() {
        etPhone.setText("");
        etPassword.setText("");
    }


// 输入框聚焦动画
private void setupFocusAnimation(final View container, final EditText editText) {
    container.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                // 聚焦时边框变橙色，并添加缩放动画
                container.setBackgroundResource(R.drawable.bg_edittext_focused);
                container.animate()
                        .scaleX(1.02f)
                        .scaleY(1.02f)
                        .setDuration(200)
                        .start();

                // 光标移动到输入框
                editText.requestFocus();
            } else {
                // 失去焦点时恢复默认样式
                container.setBackgroundResource(R.drawable.bg_edittext_normal);
                container.animate()
                        .scaleX(1.0f)
                        .scaleY(1.0f)
                        .setDuration(200)
                        .start();
            }
        }
    });

    // 点击容器获取焦点
    container.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            editText.requestFocus();
        }
    });
}

    @Override
    protected void onPause() {
        super.onPause();
        // 暂停背景动画，避免资源浪费
        if (backgroundAnimation != null && backgroundAnimation.isRunning()) {
            backgroundAnimation.stop();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 恢复背景动画
        if (backgroundAnimation != null && !backgroundAnimation.isRunning()) {
            backgroundAnimation.start();
        }
    }

    //跳转到注册页面的方法
    public void navigateToRegister(View view) {
        Intent intent = new Intent(this, RegisterActivity.class);
        startActivity(intent);
    }

}
